{% extends "base.html" %}

{% block title %}
发表主题
{% endblock %}

{% block css%}
<link href="/assets/js/wangeditor/css/wangEditor.min.css" rel="stylesheet" type="text/css" />
{% endblock %}

{% block content %}
<div style="background:#fff;padding:15px;box-sizing:border-box;">
    {% let t = topic|uw %}
    <form id="post">
        <div class="ef"><input class="input_narrow" size="40" name="title" id="title" value='{{t.title|uw}}'
                placeholder="标题" type="text"></div>
        <div class="ef">
            <select name="style" onchange="changeStyle(this)" class="select">
                <option value="1" {% if t.style|is && t.style|uw==1 %}selected{% endif %}>markdown</option>
                <option value="2" {% if t.style|is_null || t.style|uw==2 %}selected{% endif %}>html</option>
            </select>
        </div>
        {% if topic|is %}
        <div class="ef"><input class="input_narrow" size="20" name="atime" id="atime" value="{{t.atime|uw|dt}}"
                type="text">
        </div>
        {% endif %}
        <div class="ef" name="rich" {%if t.style|is && t.style|uw==1 %}style="display:block"
            {%else%}style="display:none" {%endif%}>
            <textarea rows="12" style="width: 100%;height: 350px;" id="log1">{%if t.style|is && t.style|uw==1 %}{{t.content|uw}}{%endif%}</textarea>
        </div>
        <div class="ef" name="rich" {%if t.style|is && t.style|uw==1 %}style="display:none"
            {%else%}style="display:block" {%endif%}>
            <div rows="12" style="height: 350px;" id="log2">{%if t.style|is_null || t.style|uw==2 %}{{t.content|uw|safe}}{%endif%}</div>
        </div>
        <div class="ef">
            <div id="picup">
                <img style="display:none" id="pic" width="90" height="60">上传缩略图
                <span id="delpic">删除</span>
                <input id="upload-input" type="file" accept="image/*" onchange="uploadThun(this)" />
            </div>
        </div>
        <div class="ef">
            <select name="tid" class="select">
                {% for cls in base.webclass %}
                <option value="{{cls.id|uw}}" {% if t.tid|is && cls.id.eq(t.tid) %}selected{% endif %}>{{cls.class|uw}} </option>
                {% endfor %}
            </select>
        </div>
        <div class="ef">
            <input class="input_narrow" size="40" name="tag" id="tag" value='{{t.tag|uw}}' placeholder="关键词多个用,分开"
                type="text">
        </div>
        <div class="ef">
            <textarea name="sum" placeholder="描述，为空自动提取" rows="2" id="sum"
                class="input_textarea">{{t.sum|uw}}</textarea>
        </div>
        <div class="ef">
            <input maxlength="8" name="pass" id="pass" class="input_narrow" placeholder="密码" value="{{t.pass|uw}}"
                type="text" />
        </div>
        <div class="ef">
            <input type="checkbox" id="hideEl" {% if t.hide|is && t.hide|uw==1 %}checked{% endif %} /> 私密
            <input type="checkbox" id="lockEl" {% if t.lock|is && t.lock|uw==1 %}checked{% endif %} /> 禁评
        </div>
        <input name="id" id="id" value="{{t.id|uw}}" type="hidden">
        <button id="addpost" type="button" onclick="savelog();" class="btn">
            发布
        </button>
        <span id="errmsg"></span>
    </form>
</div>
{% endblock %}

{% block script %}
<script type="text/javascript" src="/assets/js/wangeditor/wangEditor.min.js"></script>
<script type="text/javascript" src="/assets/js/html2md.js"></script>
<script type="text/javascript" src="/assets/js/showdown.min.js"></script>
<script type="text/javascript" language="javascript" src="/assets/js/laydate/laydate.js"></script>

<script>
    laydate.render({ elem: '#atime', type: 'datetime' });
    var upic = '{{t.pic|uw}}';
    var editor = new wangEditor('log2');
    editor.config.menuFixed = false;
    editor.config.menus = ['source', 'bold', 'eraser', 'forecolor', 'bgcolor', 'quote', 'fontsize', 'head', 'unorderlist', 'orderlist', 'alignleft', 'aligncenter', 'alignright', 'link', 'unlink', 'img', 'insertcode', 'fullscreen'];
    editor.config.uploadImgUrl = '/post/upload';
    editor.config.uploadImgFileName = 'picture1';
    editor.config.uploadImgFns.onload = function (resultText, xhr) {
        var obj = JSON.parse(resultText);
        if (obj.result == 200) {
            editor.command(null, 'insertHtml', '<img src="' + obj.data + '" style="max-width:100%;"/>');
        } else {
            alert(obj.message);
        }
    };
    editor.create();

    function changeStyle(t) {
        $("[name=rich]").hide();
        var style = $(t).val();
        var cur = $("[name=rich]").eq(style - 1);
        cur.show();
        var log2 = editor.$txt.html().replace(/<p>[<br>]*<\/p>/g, '').trim();
        if (style == 1 && log2 != "" && $("#log1").val().trim() == "") {
            $("#log1").val(html2md(log2));
        }
        var log1 = $("#log1").val().trim();
        if (style == 2 && log2 == "" && log1 != "") {
            const converter = new showdown.Converter();
            converter.setOption('tables', true);
            const html = converter.makeHtml(log1);
            $("#log2").html(html);
        }
    }

    if (upic != '') {
        $("#pic").attr("src", upic).show()
        $('#delpic').show()
    }
    $('#delpic').on('click', function () {//绑定鼠标划出事件
        $("#pic").attr("src", '').hide();
        $('#delpic').hide()
        upic = '';
    });
    function delpic() {

    }
    function uploadThun(input) {
        var fd = new FormData();
        fd.contentType = "multipart/form-data";
        fd.append("picture", input.files[0]);
        $.ajax({
            url: '/post/upload?thum=true',
            type: 'post',
            dataType: 'json',
            processData: false,
            contentType: false,
            data: fd,
            success: function (res) {
                if (res.result == '200') {
                    upic = res.data
                    $("#pic").attr("src", upic).show();
                    $('#delpic').show()
                }
            }
        })
    }

    document.getElementById("log1").addEventListener("paste", function (e) {  // 粘贴事件触发
        if (!(e.clipboardData && e.clipboardData.items)) return

        var pasteData = e.clipboardData || window.clipboardData // 获取剪切板里的全部内容
        pasteAnalyseResult = new Array  // 用于储存遍历分析后的结果

        for (var i = 0; i < pasteData.items.length; i++) {  // 遍历分析剪切板里的数据
            var item = pasteData.items[i]

            if ((item.kind == "string") && (item.type.match('^text/html'))) {
                pasteAnalyseResult['type'] = 'html'
                pasteAnalyseResult['data'] = item
            }
        }
        if (pasteAnalyseResult['type'] == 'html') {  // 如果剪切板有 html 格式数据,则将其转化为 markdown 格式文本,并显示出来
            pasteAnalyseResult['data'].getAsString(function (str) {
                document.getElementById("log1").value =html2md(str) 
            })
        }
    }, false);
</script>
{% endblock %}
